package io.xuan.modules.app.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class TokenManager {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 令牌过期时间，默认为1小时
    private long expire = 3600;

    // Redis中存储令牌的前缀
    private static final String TOKEN_PREFIX = "token:";

    /**
     * 生成Token并存储至Redis
     */
    public String generateToken(long userId) {
        String token = jwtUtils.generateToken(userId);
        String key = TOKEN_PREFIX + token;
        redisTemplate.opsForValue().set(key, String.valueOf(userId), expire, TimeUnit.SECONDS);
        return token;
    }

    /**
     * 验证Token是否有效
     */
    public boolean validateToken(String token) {
        String key = TOKEN_PREFIX + token;
        String userId = redisTemplate.opsForValue().get(key);
        return userId != null;
    }

    /**
     * 从Redis中移除Token
     */
    public void removeToken(String token) {
        String key = TOKEN_PREFIX + token;
        redisTemplate.delete(key);
    }
}
